/**
 * Created by fang on 2017/6/5.
 */
/**
 * Created by 009 on 2017/5/26.
 */

(function ($, window, document, undefined) {

    "use strict";

    window = (typeof window != 'undefined' && window.Math == Math)
        ? window
        : (typeof self != 'undefined' && self.Math == Math)
        ? self
        : Function('return this')()
    ;
    $.fn.testme = function (a, b, c) {
        console.info('hello.....');
        console.info(this);
        console.info($(this));
    };

    function queryTableId(tableId) {
        if(tableId === undefined) {
            return 'data_table_' + $('table').length
        }
        return tableId;
    }

    $.fn.tablebind = function (tableColumns, tableSettings) {
        var
            returnedValue,
            $wrapper = ($(this).length === 0)
                ? $('<div></div>')
                : $(this),
            settings = ( $.isPlainObject(tableSettings) )
                ? $.extend(true, {}, $.fn.tablebind.settings, tableSettings)
                : $.extend({}, $.fn.tablebind.settings),
            columns = ($.isArray(tableColumns))
                ? tableColumns
                : $.extend([], $.fn.tablebind.columns),
            key = settings.key,
            _columns = [],
            element = this,
            $element = $(this),
            $toolbar = $(this).find('div[data-section=toolBar]'),
            $table = $(this).find('table'),
            $view_add = $(this).find('div[data-section=add]'),
            table_id = queryTableId(settings.tableId),
            $view_update = $('.modal[data-section=update]and[data-table='+table_id+']'),
            $view_delete = $('.modal[data-section=delete]and[data-table='+table_id+']'),
            //instance = $module.data(moduleNamespace),
            module;


        //$modules = $(this);
        //合并列
        $.each(columns, function (idx,col) {
            col = $.isPlainObject(col)
                ? $.extend(true, {}, $.fn.tablebind.column, col)
                : $.extend({}, $.fn.tablebind.column, {label:idx,name:idx});
            col.index = idx;
            _columns.push(col);
        });


        columns = _columns;
        //
        $wrapper.data('id', table_id);
        settings.tableId = table_id;

        module = {
            initialize : function () {
                //load tool bar
                if($toolbar.length === 0) {
                    $toolbar = createToolBar();
                    $wrapper.append($toolbar);
                    $toolbar.find('.ui.calendar').calendar();
                    $toolbar.find('.ui.dropdown').dropdown();
                }
                //load table body
                if($table.length === 0) {
                    $table = createTable();
                    $wrapper.append($table);
                    $table.find('.ui.dropdown').dropdown();
                }
                //load table pag
                //load add view
                if($view_add.length === 0) {
                    $view_add = createAddView();
                    $wrapper.append($view_add);
                    $view_add.find('.ui.calendar').calendar();
                    $view_add.find('.ui.dropdown').dropdown();
                }
                //load update view
                if($view_update.length === 0) {
                    $view_update = createUpdateView();
                    $('body').append($view_update);
                    $view_update.modal();//init
                    $view_update.find('.ui.calendar').calendar();
                    $view_update.find('.ui.dropdown').dropdown();
                }

                //load delete view
                if($view_delete.length === 0) {
                    $view_delete = createDeleteView();
                    $('body').append($view_delete);
                    $view_delete.modal();
                }

   //
                //bind tool bar event
                //bind table row and row tools event
                //bind table pag event
                //bind add view event
                //bind update view event
                //bind delete view event
            }
        };


        function createToolBar() {
            var $tool = $('<div class="ui grid segment" data-section="toolBar"></div>'),
                $add = $('<div class="two wide column"><button class="ui green labeled icon button"><i class="add icon"></i>添加</button></div>'),
                $search = $('<div class="nine wide column row">' +
                    '<div><span>选择列：</span><select class="ui search dropdown"></select></div>' +
                    '<div>' +
                    '<div class="ui action left icon input"><i class="search icon"><input type="text" placeholder="Search..."></i>' +
                    '<div class="ui blue button" id="data_query">查询</div></div></div>');

            var options = '';
            $.each(columns, function () {
                options += this.searchable?'<option value="'+this.name+'">'+this.label+'</option>':'';
            });
            $search.find('select').html($search.find('select').html()+options);

            $tool.append($add).append($search);

            return $tool;
        }

        function createTable() {
            var $table = $('<table class="ui celled striped table"><thead><tr></tr></thead><tbody></tbody><tfoot></tfoot></table>'),
                $head = $table.children('thead').children('tr'),
                $foot = $table.children('tfoot').children('tr');
            $.each(columns, function () {
                $head.append('<th>'+this.label+'</th>');
            });
            $head.append('<th class="three wide">操作</th>');
            $table.append($head);
            $foot.append('<th colspan="'+columns.length+'">' +
                '<div class="ui pagination label floated left">' +
                '<strong>0</strong><span class="section">条</span>' +
                '<strong>0</strong><span class="section">页</span>' +
                '<span>每页：</span>' +
                '<select name="pagesize" class="ui mini dropdown">' +
                '<option value="20" selected="selected">20</option>' +
                '<option value="30">30</option>' +
                '<option value="50">50</option>' +
                '<option value="100">100</option>' +
                '</select>' +
                '<span>条</span>' +
                '</div>' +
                '<div class="ui mini right floated pagination menu "></div></th>');
            return $table;
        }

        /**
         * 添加到Dom中后务必初始化组件，如初始化calendar，初始化dropdown等
         * @returns {*|HTMLElement}
         */
        function createAddView() {
            var $view = $('<div class="ui segment" style="display: none;"></div>');
            $view.data('section', 'add');

            var $form_container = $('<div class="ui segment"><div class="ui huge header"><i class="add user icon"></i>添加用户</div><div class="content"></div></div>'),
                $form = $('<form class="ui form"></form>');
            $form.append('<div class="ui divider"></div>');
            $.each(columns, function (idx, col) {
                if(!col.writable) return true;
                var $field = $($.fn.tablebind.component.inline[col.type]);
                $field
                    .append($.fn.tablebind.component.label['text'](col.name))
                    .append($.fn.tablebind.component.input[col.type]);
                if(col.required === true) $field.addClass('required');
                if($.fn.tablebind.component.bind[col.type] === undefined);
                else {
                    $.fn.tablebind.component.bind[col.type]($field);
                }
                //
                $form.append($field);
            });
            var $actions = $('<div class="actions">' +
                '<div class="ui button">取消</div>' +
                '<div class="ui primary button">保存</div>' +
                '</div>');
            $form.append('<div class="ui divider"></div>').append($actions)
                .append('<div class="ui error message"></div>');
            $form_container.find('.content').append($form);

            $actions.children('button').eq(0).click(function () {
                //
                $wrapper.children('div[data-section=toolBar]').slideToggle('slow');
                $wrapper.children('table').slideToggle('slow');
                //
                $view.slideToggle('slow');
            });

            $actions.children('button').eq(1).click(function () {
                $form.form('validate form');
            });
            //form validate rules
            var fields = {};
            $.each(columns, function (idx, col) {
                if (!col.writable) return true;
                fields[col.name] = {
                    identifier : col.name,
                    rules : col.validate
                }
            });

            $form.form({
                fields : fields,
                onSuccess : function (event, fields) {
                    var token = $("meta[name='_csrf']").attr("content");
                    var header = $("meta[name='_csrf_header']").attr("content");
                    var headers = {};
                    headers[header] = token;
                    //post data
                    $.ajax({
                        type : 'POST',
                        url : settings.addUrl,
                        data : JSON.stringify(fields),
                        contentType : "application/json",
                        dataType : 'json',
                        headers : headers,
                        success: function (data){
                            if(data.code === 1) {
                                $.each(data.data, function (id, error) {
                                    $form.form('add prompt', id);
                                    console.log(error);
                                });
                                $form.form('add errors', data.data);
                            } else {
                                //location.reload();
                                settings.onAddSucess($view, $wrapper, table_id);
                            }
                            console.log(data);
                        }
                    }).done(function (data) {
                        console.info('done');
                    }).fail(function (data) {
                        console.info('fail');
                        settings.onAddFail(data, $view, $wrapper, table_id);
                    }).always(function () {
                        console.info('always');
                    });
                },
                //保留
                onFailure : function (formErrors, fields) {
                    console.log(formErrors);
                    console.log(fields);
                }

            });

            return $view;
        }

        function createUpdateView() {
            var $view = $('<div class="ui modal segment"></div>');
            $view.data('section', 'update');
            $view.data('id', table_id);

            $view.html('<i class="close icon massive"></i><div class="header">编辑</div>');
            var $content = $('<div class="content"><form class="ui form"></form></div>'),
                $actions = $('<div class="actions"><button class="ui button">取消</button>' +
                    '<button class="ui primary button">保存</button></div>'),
                $key = $('<input type="hidden">'),
                $form = $content.children('form');
            $key.data('name', 'id');
            $form.append($key);

            $.each(columns, function (idx, col) {
                if(!col.updatable) return true;
                var $field = $($.fn.tablebind.component.inline[col.type]);
                $field
                    .append($.fn.tablebind.component.label['text'](col.name))
                    .append($.fn.tablebind.component.input[col.type]);
                if(col.required === true) $field.addClass('required');
                if($.fn.tablebind.component.bind[col.type] === undefined);
                else {
                    $.fn.tablebind.component.bind[col.type]($field);
                }
                $form.append($field);
            });
            $form.append('<div class="ui error message"></div>');

            $view.append($content);
            $view.append($actions);

            $actions.children('button').eq(0).click(function () {
                $view.modal('hide');
            });
            $actions.children('button').eq(1).click(function () {
                $form.form('validate form');
            });

            //form validate rules
            var fields = {};
            $.each(columns, function (idx, col) {
                if (!col.updatable) return true;
                fields[col.name] = {
                    identifier : col.name,
                    rules : col.validate
                }
            });

            $form.form({
                fields : fields,
                onSuccess : function (event, fields) {
                    var token = $("meta[name='_csrf']").attr("content");
                    var header = $("meta[name='_csrf_header']").attr("content");
                    var headers = {};
                    headers[header] = token;
                    //post data
                    $.ajax({
                        type : 'POST',
                        url : settings.updateUrl,
                        data : JSON.stringify(fields),
                        contentType : "application/json",
                        dataType : 'json',
                        headers : headers,
                        success: function (data){
                            if(data.code === 1) {
                                $.each(data.data, function (id, error) {
                                    $form.form('add prompt', id);
                                    console.log(error);
                                });
                                $form.form('add errors', data.data);
                            } else {
                                //location.reload();
                                settings.onModSuccess($view, $wrapper, table_id);
                            }
                            console.log(data);
                        }
                    }).done(function (data) {
                        console.info('done');
                    }).fail(function (data) {
                        console.info('fail');
                        settings.onModFail(data, $view, $wrapper, table_id);
                    }).always(function () {
                        console.info('always');
                    });
                },
                //保留
                onFailure : function (formErrors, fields) {
                    console.log(formErrors);
                    console.log(fields);
                }

            });

            return $view;
        }

        function createDeleteView() {

            var $view = $('<div class="ui basic modal small" id="delete_view"></div>'),
                $header = $('<div class="ui icon header"><i class="warning circle icon red"></i>正在进行危险操作...</div>'),
                $content = $('<div class="content"><i class="info circle icon"></i>确定<span class="red">删除数据</span>?</div>'),
                $hide_key = $('<input type="hidden">'),
                $actions = $('<div class="actions">' +
                    '<div class="ui red basic cancel inverted button"><i class="remove icon"></i>否</div>' +
                    '<div class="ui green ok inverted button"><i class="checkmark icon"></i>是</div>' +
                    '</div>');
            $view.html($header);
            $content.append($hide_key);
            $view.append($content);
            $view.append($actions);
            $actions.children('.cancel').click(function () {
                view.modal('hide');
            });
            $actions.children('.ok').click(function () {
                var id = content.children('input').val(),
                    post_body = {id:id};

                var token = $("meta[name='_csrf']").attr("content");
                var header = $("meta[name='_csrf_header']").attr("content");
                var headers = {};
                headers[header] = token;
                //post data
                $.ajax({
                    type : 'POST',
                    url : settings.deleteUrl,
                    data : post_body,
                    contentType : "application/json",
                    dataType : 'json',
                    headers : headers,
                    success: function (data){
                        if(data.code === 1) {
                            $.each(data.data, function (id, error) {
                                console.log(id+':'+error);
                            });

                        } else {
                            //location.reload();
                            settings.onDelSuccess($view, $wrapper, table_id);
                        }
                        console.log(data);
                    }
                }).done(function (data) {
                    console.info('done');
                }).fail(function (data) {
                    console.info('fail');
                    settings.onDelFail(data, $view, $wrapper, table_id);
                }).always(function () {
                    console.info('always');
                });

            });

            return $view;
        }


        $.fn.tablebind.column = {
            index : 0,
            label : '',               //显示标签（用于表头以及表单标签）
            type : 'text',                     //数据类型（用于构建表格单元格以及表单输入框）
            name : '',                 //字段名（和后台请求保持一致，必须唯一）
            required : false,                 //是否必须（添加/修改校验）
            writable : true,                 //是否可写
            updatable : true,                //是否可更新
            searchable : false,               //是否可搜索
            enableValidate : true,           //是否启用校验
            //validate: function () {return true}    //自定义校验函数
            validate: []    //自定义校验函数
        }

        var a = {
            b : {
                b1 : function () {
                    console.info(1);
                    console.info(arguments);
                },
                label : {
                    text : function () {
                        var label_text = arguments.length > 0 ? arguments[0] : '';
                        return '<label>'+label_text+'</label>';
                    }
                }
            }
        };
        console.log(a.b['label']['text']('a1','a2'));

        $.fn.tablebind.component = {
            inline : {
                text : '<div class="inline field"></div>',
                password : '<div class="inline field"></div>',
                image : '<div class="inline field"></div>',
                date : '<div class="ui calendar inline field"></div>',
                datetime : '<div class="ui calendar inline field"></div>',
                time : '<div class="ui calendar inline field"></div>',
                checkbox : '<div class="inline field"></div>',
                select : '<div class="inline field"></div>',
                textarea : '<div class="inline field"></div>',
                file : '<div class="inline field"></div>',
                currency : '<div class="inline field"></div>',

            },
            input : {
                text : '<input type="text">',
                password : '<input type="password">',
                image : '<input type="file" style="display: none;"><img class="ui avatar image" src=""><div class="ui icon button"><i class="upload icon"></i></div>',
                date : '<div class="ui input left icon"><i class="calendar icon"></i><input type="text"></div>',
                datetime : '<div class="ui input left icon"><i class="calendar icon"></i><input type="text"></div>',
                time : '<div class="ui input left icon"><i class="calendar icon"></i><input type="text"></div>',
                checkbox : '<div class="ui checkbox"><input type="checkbox" class="hidden"></div>',
                select : '<select class="ui dropdown"></select>',
                number : '',
                email : '',
                textarea : '<textarea rows="4"></textarea>',
                file : '<input type="file" style="display: none;"><div class="ui mini label"></div><div class="ui icon button"><i class="upload icon"></i></div>',
                currency : '<div class="ui input left icon"><i class="yen icon"></i><input type="text"></div>'
            },
            label : {
                text : function () {
                    var label_text = arguments.length > 0 ? arguments[0] : '';
                    return '<label>'+label_text+'</label>';
                }
            },
            bind : {
                image : function () {
                    var $ele = arguments.length > 0 ? $(arguments[0]) : $('');
                    $ele.find('div.ui.icon.button').click(function () {
                        $ele.children('input[type=file]').click();
                    });
                    $ele.children('input[type=file]').on('change', function (e) {
                        if(e.target.files && e.target.files[0]) {
                            $ele.find('img').attr('src', URL.createObjectURL(e.target.files[0]));
                        }
                    });
                },
                file : function () {
                    var $ele = arguments.length > 0 ? $(arguments[0]) : $('');
                    $ele.find('div.ui.icon.button').click(function () {
                        $ele.children('input[type=file]').click();
                    });
                    $ele.children('input[type=file]').on('change', function (e) {
                        if(e.target.files && e.target.files[0]) {
                            $ele.find('div.ui.label').text(e.target.files[0].name);//file.size file.type
                        }
                    });
                }
            },
            validate : {

            }
        };






        function buildAddView() {



            view.html(form_container);
            field_date.calendar();
            field_register_date.calendar();
            //event
            field_avatar.children('div.ui.icon.button').click(function () {
                $(this).parent().children('input[type=file]').click();
            });
            field_avatar.children('input[type=file]').on('change', function (e) {
                console.info($(this).parent().children('img'));
                console.info(URL.createObjectURL(e.target.files[0]));
                if(e.target.files && e.target.files[0]) {
                    $(this).parent().children('img').attr('src', URL.createObjectURL(e.target.files[0]));
                }
            });

            actions.children('.ui.button').eq(1).click(function () {
                console.info('save');
                form.form('validate form');
            });
            actions.children('.ui.button').eq(0).click(function () {
                console.info('cancel');
                table_container.children('#table_view_admin_body').slideToggle('slow');
                table_container.children('#add_view').slideToggle('slow');
            });


            form.form({
                fields: {
                    nick : {
                        identifier : "name",
                        rules : [{type : 'empty', prompt : '昵称不能为空'}]

                    },
                    avatar : {
                        identifier : 'avatar',
                        rules : [{type : 'empty', prompt : '请选择头像'}]
                    },
                    account : {
                        identifier : 'account',
                        rules : [{type : 'empty', prompt : '账户不能为空'},
                            //{type : 'minCount[9]', prompt : '最少需要9位'},
                            {type : 'number', prompt : '账号必须为数字'}]
                    },
                    email : {
                        identifier : 'email',
                        rules : [{type : 'empty', prompt : '邮箱不能为空'},
                            {type : 'email', prompt : '请输入有效的邮箱'}]
                    },
                    date : {
                        identifier : 'date',
                        rules : [{type : 'regExp[/^[\\d]{4}[-][\\d]{1,2}[-][\\d]{1,2}[\\s][\\d]{1,2}[:][\\d]{1,2}[:][\\d]{1,2}$/]', prompt : '日期格式错误'}]
                    },
                    createTime : {
                        identifier : 'createTime',
                        rules : [{type : 'regExp[/^[\\d]{4}[-][\\d]{1,2}[-][\\d]{1,2}[\\s][\\d]{1,2}[:][\\d]{1,2}[:][\\d]{1,2}$/]', prompt : '注册日期日期格式错误'}]
                    }
                },

                onSuccess : function (event, fields) {
                    console.info(JSON.stringify(fields));

                    var token = $("meta[name='_csrf']").attr("content");
                    var header = $("meta[name='_csrf_header']").attr("content");
                    var headers = {};
                    headers[header] = token;

                    $.ajax({
                        type : 'POST',
                        url : '/user/system/add',
                        data : JSON.stringify(fields),
                        contentType : "application/json",
                        dataType : 'json',
                        headers : headers,
                        success: function (data){
                            if(data.code === 1) {
                                $.each(data.data, function (id, error) {
                                    form.form('add prompt', id);
                                    console.log(error);
                                });
                                form.form('add errors', data.data);

                            } else {
                                location.reload();
                            }
                            console.log(data);
                        }
                    }).done(function (data) {
                        console.info('done');
                    }).fail(function (data) {
                        console.info('fail');
                    }).always(function () {
                        console.info('always');
                    });
                    /*
                     var token = $("meta[name='_csrf']").attr("content");
                     var header = $("meta[name='_csrf_header']").attr("content");

                     form.api({
                     method : 'POST',
                     url : '/user/system/add',
                     dataType : 'json',
                     data : JSON.stringify(fields),
                     beforeXHR : function (xhr) {
                     xhr.setRequestHeader(header, token);
                     return xhr;
                     },
                     onComplete : function (response, element, xhr) {
                     console.log(response);
                     }
                     });
                     */
                },
                onFailure : function (formErrors, fields) {
                    console.log(formErrors);
                    console.log(fields);
                }
            });




            //show
            table_container.children('#table_view_admin_body').slideToggle('slow');
            table_container.children('#add_view').slideToggle('slow');

        }


        /*

         */
        return (returnedValue !== undefined)
            ? returnedValue
            : this
            ;


        var init = function () {
            var tool = table.find('div[data-section=toolBar]');
            if(tool.length === 0) {
                table.html(initToolBar());
            }
            table.append(initTable());
        }



        var initTable = function () {

        }

        var refresh = function (data) {
            var $table = table.children('table'),
                $tbody = $table.find('tbody');
            reloadPagBar($table, data.total, data.page, data.pageSize);
            $.each(data.rows, function (idx, row) {
                var $tr = $('<tr></tr>');
                $tr.data('id', row[key]);
                $tr.append('<td>'+((data.page-1)*data.pagesize + (idx+1))+'</td>');

                $.each(columns, function (idx, col) {
                    var $td = $('<td></td>');
                    if(idx === 0) {
                        $td.text(((data.page-1)*data.pagesize + (idx+1)));
                        $tr.append($td);
                        return true;
                    }
                    $td.data('name', col.name);
                    $td.text(row[col.name]);
                    $tr.append($td);
                });
                $tr.append('<td data-name="tools">' +
                    '<div>' +
                    '<button class="ui mini teal labeled icon button"><i class="edit icon"></i>编辑</button>' +
                    '<button class="ui mini right floated red labeled icon button"><i class="delete icon"></i>删除</button>' +
                    '</div>' +
                    '</td>');
                $tbody.append($tr);

            });
        }














        function reloadPagBar(table, total, current_page, page_size) {
            var total_page = Math.ceil(total / page_size);
            var label_bar = table.find('.pagination.label'),
                menu_bar = table.find('.pagination.menu'),
                page_labels = label_bar.children('strong'),
                page_size_select = label_bar.find('select');
            page_labels.eq(0).text(total);
            page_labels.eq(1).text(total_page);
            page_size_select.dropdown('set selected', page_size);

            //小于等于6页 全部显示

            //大于6页 前5页全部显示，中间省略，最后一页显示
            //当前页小于5
            //第一页显示，省略，中间3页（上一页，当前页，下一页），省略，最后一页
            //当前页大于等于5，但不是最后5页
            //当前页为最后5页
            //第一页，省略，最后5页连续
            //最开始5页
            //前一页，后一页
            var $pre = $('<a class="icon item left"><i class="left chevron icon"></i>上一页</a>'),
                $next = $('<a class="icon item right">下一页<i class="right chevron icon"></i></a>'),
                $items = $('<div></div>');
            if(total_page < 7) {
                //全部显示
                var start = 0;
                while (start < total_page) {
                    start ++;
                    if(start === current_page) {
                        $items.append('<a class="item active">'+start+'</a>');
                    }
                    else {
                        $items.append('<a class="item">'+start+'</a>');
                    }
                }
            } else if(current_page < 5) {
                //前5页，省略，最后一页
                var start = 0;
                while (start < 5) {
                    start ++;
                    if(current_page === start) {
                        $items.append('<a class="item active">'+start+'</a>');
                    } else {
                        $items.append('<a class="item">'+start+'</a>');
                    }
                }
                $items.append('<a class="item disabled">...</a>');
                $items.append('<a class="item">'+total_page+'</a>');

            } else if((total_page - current_page) < 4) {
                //第一页，省略，后5页
                $items.append('<a class="item">1</a>');
                $items.append('<a class="item disabled">...</a>');

                var start = total_page - 4;
                while (start <= total_page) {
                    if(start === current_page) {
                        $items.append('<a class="item active">'+start+'</a>');
                    } else {
                        $items.append('<a class="item">'+start+'</a>');
                    }
                    start ++;
                }
            } else {
                //第一页，省略，中间3页，省略，最后一页
                $items.append('<a class="item">1</a>');
                $items.append('<a class="item disabled">...</a>');
                $items.append('<a class="item">'+(current_page-1)+'</a>');
                $items.append('<a class="item active">'+(current_page)+'</a>');
                $items.append('<a class="item">'+(current_page+1)+'</a>');
                $items.append('<a class="item disabled">...</a>');
                $items.append('<a class="item">'+total_page+'</a>');
            }
            //
            if(current_page === 1) {
                $pre.addClass('disabled');
            }
            if(current_page === total_page) {
                $next.addClass('disabled')
            }
            menu_bar.html($pre).append($items.html()).append($next);
        }


        function bindPagEvents() {

            var $table = table.children('table'),
                page = $table.children('input[data-name=page]').val();

            $table.find('tfoot').find('.pagination.menu').find('a.item:not(.icon):not(.active):not(.disabled)').each(function (idx, e) {
                $(e).click(function () {
                    var json_data = loadData($(this).text());
                    if(json_data.code === 1) {
                        refresh(json_data);
                    }
                });
            });
        }


        function loadData(pageNo) {
            var $table = table.children('table'),jsondata={};
            pageNo = Number.parseInt(pageNo);
            if(isNaN(pageNo)) return;
            var token = $("meta[name='_csrf']").attr("content");
            var header = $("meta[name='_csrf_header']").attr("content");
            var headers = {};
            headers[header] = token;
            var pageSize = $table.find('tfoot').find('select[name=pagesize]').val(),
                page_size = Number.parseInt(pageSize);
            if(isNaN(page_size)) return;

            $.ajax({
                type : 'GET',
                url : settings.dataUrl+'?size='+page_size+'&page='+pageNo,
                headers : headers,
                success: function (data){
                    //if(data.code === 1) {
                    //    alert(data.data);
                    //} else {
                    //    location.reload();
                    //}
                    if(data.code === 1) {
                        jsondata = data;
                    }
                    console.log(JSON.stringify(data));
                }
            }).done(function (data) {
                console.info('done');
            }).fail(function (data) {
                console.info('fail');
            }).always(function () {
                console.info('always');
            });

            return jsondata;
        }



        $modules.each(function(){
            var module = $(this);
        });
    };

    //publish default setting
    $.fn.tablebind.settings = {
        key : "id",
        tableId : undefined,
        dbClickEditable : false,
        table : 'table',
        erorrClass : '',
        editorClass : '',
        changeClass : '',
        //加载table的url
        dataUrl : '',
        //添加数据url
        addUrl : '',
        //更新数据url
        updateUrl : '',
        //删除数据url
        deleteUrl : '',
        //更新成功后执行函数
        onModSuccess : function ($view, $wrapper, id) {
            //default refresh table
            //modal hide
        },
        onModFail : function (error, $view, $wrapper, id) {

        },
        //创建成功后执行函数
        onAddSucess : function ($view, $wrapper, id) {
            //default refresh table
            //toggle form
        },
        //
        onAddFail : function ($view, $wrapper, id) {
            //show fail cause reason
        },
        //删除成功后执行函数
        onDelSuccess : function ($view, $wrapper, id) {
            //default refresh table
            //modal hide
        },
        onDelFail : function (error, $view, $wrapper, id) {

        }
    };
    $.fn.tablebind.columns = [
        {
            label : '#',               //显示标签（用于表头以及表单标签）
            name : 'rowno',                 //字段名（和后台请求保持一致，必须唯一）
            writable : false,                 //是否可写
            updatable : false,                //是否可更新
            enableValidate : false,           //是否启用校验
        }
    ];
    $.fn.tablebind.column = {
        index : 0,
        label : '',               //显示标签（用于表头以及表单标签）
        type : 'text',                     //数据类型（用于构建表格单元格以及表单输入框）
        name : '',                 //字段名（和后台请求保持一致，必须唯一）
        required : false,                 //是否必须（添加/修改校验）
        writable : true,                 //是否可写
        updatable : true,                //是否可更新
        searchable : false,               //是否可搜索
        enableValidate : true,           //是否启用校验
        validate: function () {return true}    //自定义校验函数
    }



    var type = [
        "text",
        "checkbox",
        "select",
        "number",
        "currency",
        "email",
        "image",
        "textarea",
        "file",
        "date",
        "time",
        "datetime"
    ];
})(jQuery, window, document);